package net.openmob.mobileimsdk.android.demo.event;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import net.openmob.mobileimsdk.android.demo.MainActivity;
import net.openmob.mobileimsdk.android.demo.SpeechUtils;
import net.openmob.mobileimsdk.android.event.ChatTransDataEvent;
import net.openmob.mobileimsdk.server.protocal.ErrorCode;

/**
 * 与IM服务器的数据交互事件在此ChatTransDataEvent子类中实现即可。
 *
 * @author x55admin, 20170501
 * @version.1.1
 */
public class ChatTransDataEventImpl implements ChatTransDataEvent {
    private final static String TAG = ChatTransDataEventImpl.class.getSimpleName();
    private android.os.Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                String dataContent = (String) msg.obj;
                if (mainActivity != null) {
                    synchronized (dataContent) {
                        SpeechUtils.getInstance(mainActivity).speakText(dataContent);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            Log.e("ChatTransDataEventImpl", e.getMessage());
                        }
                    }

                }
            }
        }
    };
    private MainActivity mainActivity = null;
    @Override
    public void onTransBuffer(String fingerPrintOfProtocal, String userid, String dataContent, int typeu) {
        Log.d(TAG, "【DEBUG_UI】[typeu=" + typeu + "]收到来自用户" + userid + "的消息:" + dataContent);
        if (mainActivity != null) {
            Toast.makeText(mainActivity, userid + "说：" + dataContent, Toast.LENGTH_SHORT).show();
            this.mainActivity.showIMInfo_black(userid + "说：" + dataContent);
            //发消息
            Message msg = Message.obtain();
            msg.what = 0;
            msg.obj = dataContent;
            handler.sendMessage(msg);

        }
    }

    public ChatTransDataEventImpl setMainActivity(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
        return this;
    }

    @Override
    public void onErrorResponse(int errorCode, String errorMsg) {
        Log.d(TAG, "【DEBUG_UI】收到服务端错误消息，errorCode=" + errorCode + ", errorMsg=" + errorMsg);

        if (errorCode == ErrorCode.ForS.RESPONSE_FOR_UNLOGIN)
            this.mainActivity.showIMInfo_brightred("服务端会话已失效，自动登陆/重连将启动! (" + errorCode + ")");
        else
            this.mainActivity.showIMInfo_red("Server反馈错误码：" + errorCode + ",errorMsg=" + errorMsg);
    }
}
